#include "threadprocess.h"
#include "processes.h"
#include "macro.h"
#include <QDebug>

ThreadProcess::ThreadProcess(QObject *parent) :
    QThread(parent)
{

}

void ThreadProcess::run()
{
    QFile file(":/others/config.txt");

    if(!file.exists())
    {
        emit sigErrorInfo("Config file not found! Adapters not started.");
        return;
    }

    if (!file.open(QIODevice::ReadOnly|QIODevice::Text ))
    {
        emit sigErrorInfo("Config file can't be opened! Adapters not started.");
        return;
    }
    else
    {
        QByteArray text=file.readAll();
        QList <QByteArray> listText=text.split('\n');
        qint8 adapterCount=listText.size();
        for(int n=0;n<adapterCount;n++)
        {
            QList <QByteArray> listItems=listText.at(n).split('\t');
            if(listItems.size()!=2)
                continue;
            else
            {
                QByteArray adapterName=listItems.at(0);
                quint16 port=listItems.at(1).toUShort();
                Processes *processClass=new Processes(adapterName,port);
                listProcesses.append(processClass);
                connect(processClass,SIGNAL(sigErrorInfo(QString)),this,SIGNAL(sigErrorInfo(QString)));
                connect(processClass,SIGNAL(sigProcessError(QByteArray,QByteArray)),this,SIGNAL(sigProcessError(QByteArray,QByteArray)));
                connect(processClass,SIGNAL(sigProcessFinished(QByteArray,int,QByteArray)),this,SIGNAL(sigProcessFinished(QByteArray,int,QByteArray)));
                connect(processClass,SIGNAL(sigProcessStarted(QByteArray)),this,SIGNAL(sigProcessStarted(QByteArray)));
                connect(processClass,SIGNAL(sigProcessStateChanged(QByteArray,QByteArray)),this,SIGNAL(sigProcessStateChanged(QByteArray,QByteArray)));
                connect(this,SIGNAL(sigProcessShow(QByteArray)),processClass,SLOT(slotProcessShow(QByteArray)));
                connect(this,SIGNAL(sigProcessHide(QByteArray)),processClass,SLOT(slotProcessHide(QByteArray)));

                processClass->start(adapterName);
            }
        }
    }

    exec();
}

void ThreadProcess::slotTestProcessStarted(QByteArray processName)
{

}

ThreadProcess::~ThreadProcess()
{
    for(int n=listProcesses.size();n>0;n--)
    {
        listProcesses.at(n-1)->kill();
        listProcesses.at(n-1)->deleteLater();
    }
    exit(0);
    wait(500);
}

